#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define CNO 4

#define swap(type, a, b) do{ type x=a; a=b; b=x; }while(0)

char **cptr = NULL;

char **eptr = NULL;

char *wordfile = "./wordbook.txt";
char *wordstatf = "./wordbook_stat.txt";

int QNO;

void print_cand(const int *c, int sw)
{
    for (int i=0; i<CNO; ++i) {
        printf("(%d)%-12s", i+1, sw ? cptr[c[i]] : eptr[c[i]]);
    }
}

void locfree(void)
{
    int i;
    for (i=0; i<QNO; ++i) {
        if (cptr[i] != NULL) free(cptr[i]);
        if (eptr[i] != NULL) free(eptr[i]);
    }

    free(cptr); free(eptr);
}

int read_words(void)
{
    int i;
    FILE *fp;

    if ((fp = fopen(wordstatf, "r")) == NULL)
        return 1;

    fscanf(fp, "%d", &QNO);

    if ((cptr = (char **)calloc(QNO, sizeof(char *))) == NULL) return 1;
    if ((eptr = (char **)calloc(QNO, sizeof(char *))) == NULL) return 1;

    if ((fp = fopen(wordfile, "r")) == NULL)
        return 1;

    for (i=0; i<QNO; ++i) {
        char ctmp[127], etmp[127];

        fscanf(fp, "%s %s", etmp, ctmp);

        if ((cptr[i] = (char *)malloc(strlen(ctmp) + 1)) == NULL) return 1;
        if ((eptr[i] = (char *)malloc(strlen(etmp) + 1)) == NULL) return 1;
        strcpy(cptr[i], ctmp);
        strcpy(eptr[i], etmp);
    }

    return 0;
}

int make_cand(int *c, int n)
{

    c[0] = n;
    int i, j;

    int x;

    for (i=1; i<CNO; ++i) {
        do {
            x = rand() % QNO;

            for (j=0; j<i; ++j) {
                if (x == c[j]) break;
            }
        } while (i != j);

        c[i] = x;
    }

    i = rand() % CNO;

    swap(int, c[i], c[0]);

    return i;
}

int main(void)
{
    int i;

    int nq, pq;

    int na;     //正确答案的编号

    int sw;     //0中文 1英文

    int retry;
    int cand[CNO];  //选项索引值

    srand(time(NULL));

    if (read_words() == 1) {
        locfree();
        fprintf(stderr, "\a单词文件读取失败.\n");
        return 1;
    }

    pq = QNO;

    do {

        do {
            nq = rand() % QNO;
        } while (nq == pq);

        sw = rand() % 2;

        make_cand(cand, nq);

        for (i=CNO-1; i>0; --i) {
            int s = rand() % (i+1);
            swap(int, cand[s], cand[i]);
        }

        printf("哪一个是%s?\n", sw? eptr[nq]: cptr[nq]);

        print_cand(cand, sw);

        putchar('\n');

        for (int i=0; i<CNO; ++i) {
            if (cand[i] == nq) {
                na = i+1;
                break;
            }
        }

        int no;
        do {
            printf("请回答: ");

            scanf("%d", &no);
            if (no != na) {
                printf("回答错误.\n");
            }
        } while (no != na);

        pq = nq;

        puts("回答正确.");

        printf("再来一次?..0-否/1-是: ");

        scanf("%d", &retry);
    } while (retry == 1);

    for (int i=0; i<QNO; ++i) {
        free(cptr[i]);
        free(eptr[i]);
    }

    free(cptr); free(eptr);

    return 0;
}
